package com.hsh.erp.aspect;

import com.hsh.erp.domain.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局拦截异常处理器
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    /**
     * 异常拦截处理逻辑
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        // MethodArgumentNotValidException异常是@Valid的异常
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            log.info("数据验证不通过");
            //返回异常消息
            return Result.fail(methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            StringBuilder stringBuilder = new StringBuilder();
            for (FieldError fieldError : bindException.getFieldErrors()) {
                stringBuilder.append("字段").append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append("；\n");
            }
            return Result.fail(stringBuilder);
        }
        return Result.fail(e.getMessage());

    }
}